package com.qst.survey.controller;

import com.alibaba.excel.EasyExcel;
import com.qst.survey.entity.QuestionAnswer;
import com.qst.survey.entity.Replay;
import com.qst.survey.pojo.Result;
import com.qst.survey.pojo.StatusCode;
import com.qst.survey.pojo.TopicData;
import com.qst.survey.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * @Description: 文件下载controller
 */

@RequestMapping("/file")
@CrossOrigin
@Controller
public class FileController {

    @Autowired
    QuestionService questionService;

    /**
     * 根据id下载对应的投票数据,并压缩成zip文件
     *
     * @param response
     * @param id
     */
    @GetMapping("/excel/{id}")
    public void excel(HttpServletResponse response, @PathVariable Integer id) {
        List<TopicData> allData = questionService.findAllData(id);
        allData.forEach(System.out::println);
        List<List<Replay>> listType0 = new ArrayList<>();
        List<List<QuestionAnswer>> listType1 = new ArrayList<>();
        for (TopicData topicData : allData
        ) {
            if (topicData.getTopicType() == 0) {
                listType0.add((List<Replay>) topicData.getData());
            } else if (topicData.getTopicType() != 0) {
                listType1.add((List<QuestionAnswer>) topicData.getData());
            }
        }
        List type0 = new ArrayList<>();
        List type1 = new ArrayList();
        for (List<Replay> list : listType0) {
            for (Replay replay : list
            ) {
                type0.add(replay);
            }
        }
        for (List<QuestionAnswer> list : listType1) {
            for (QuestionAnswer questionAnswer : list
            ) {
                type1.add(questionAnswer);
            }
        }
        listType0.forEach(System.out::println);
        listType1.forEach(System.out::println);
        type0.forEach(System.out::println);
        type1.forEach(System.out::println);
        String replayDataFileName = UUID.randomUUID().toString().replace("-", "") + ".xlsx";
        EasyExcel.write(replayDataFileName, Replay.class)
                //代表要在Excel的哪个页面写入数据,如果不指定,默认在第一个页面,第一个页面sheet值为0
                .sheet()
                //表示写出数据,类型为list集合
                .doWrite(type0);
        String selectDataFileName = UUID.randomUUID().toString().replace("-", "") + ".xlsx";
        EasyExcel.write(selectDataFileName, QuestionAnswer.class)
                //代表要在Excel的哪个页面写入数据,如果不指定,默认在第一个页面,第一个页面sheet值为0
                .sheet()
                //表示写出数据,类型为list集合
                .doWrite(type1);
        //将生成的excel文件保存到List集合
        List<File> files = new ArrayList<File>();
        files.add(new File(replayDataFileName));
        files.add(new File(selectDataFileName));
        toZip(files, response);
    }


    public static void toZip(List<File> srcFiles, HttpServletResponse response) throws RuntimeException {
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=data.zip");
        } catch (IOException e) {
            e.printStackTrace();
        }
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                    for (File file : srcFiles
                    ) {
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}


